package com.acp.controller.uploadphotofile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;


import com.acp.context.Config;
import com.acp.model.UploadFile;
import com.acp.result.JsonData;
import com.acp.result.ResultInfo;
import com.acp.result.ResultUtil;
import com.acp.service.UploadFileService;
import com.acp.util.UUIDBuild;
import com.hazelcast.com.eclipsesource.json.Json;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * All rights Reserved, Designed By 姑苏区政府大数据中心
 *
 * @version V1.0
 * @Title: null.java
 * @Package com.dci.controller.construction
 * @Description: 上传压缩文件
 * @author: 张星亮
 * @date: 2019/4/5
 * @Copyright: 2019 姑苏区政府大数据中心. All rights reserved.
 * 注意：本内容仅限于姑苏区政府大数据中心内部传阅，禁止外泄以及用于其他的商业目
 */

@Controller
@RequestMapping("/photo")
public class FileUploadController {

    @Value("${upload.path}")
    private String path;

    @Value("${upload.urlIP}")
    private String urlIP;

    @Resource
    private UploadFileService uploadFileService;

    /**
     * 上传单个文件
     * @param request
     * @param files
     * @return OperatorResult 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping(value = "/uploadOne", method = RequestMethod.POST)
    public ResultInfo uploadOne(HttpServletRequest request, @RequestParam("file") MultipartFile[] files) {

        String address = "rw0001";
        String filePath = path + File.separator + address + "/";
        String fileNames = "";
        if (files.length != 0) {
            for (MultipartFile file : files) {
                String fileName = file.getOriginalFilename();
                if (fileNames == "") {
                    fileNames += fileName;
                } else {
                    fileNames += ',' + fileName;
                }
                File fileDir = new File(filePath);
                if (!fileDir.exists()) {
                    fileDir.mkdirs();
                }
                try {
                    file.transferTo(new File(fileDir.getAbsolutePath(), fileName));
                } catch (IOException e) {
                    continue;
                }
            }
        }
        // 数据库存储的相对路径
        String urlPath = urlIP + address + "/";
        System.out.println(urlPath);
        return ResultUtil.createFail(Config.MESSAGE,906,null);
    }

    /**
     * 规定压缩文件类型
     */
    private static final String[] extensionPermit = { "zip", "rar", "json"};

    /**
     * 上传文件
     * @param request
     * @param files
     * @return OperatorResult 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    @ResponseBody
    public OperatorResult upload(HttpServletRequest request, @RequestParam("photo") MultipartFile[] files, @RequestParam("type") String type) {
        OperatorResult result = new OperatorResult();
        String saveDirectoryPath = "C://uploadFiles";
        String saveZipPath = saveDirectoryPath + "/zips/";
        String saveRarPath = saveDirectoryPath + "/rars/";
        String saveJsonPath = saveDirectoryPath + "/jsons/";
        String saveProjectPath = saveDirectoryPath ;
        File saveZipDirectory;
        File saveRarDirectory;
        File saveJsonDirectory;
        try {
            // 上传json文件
            for (MultipartFile file : files) {
                if (!file.isEmpty()) {
                    String fileName = file.getOriginalFilename();
                    String fileExtension = FilenameUtils.getExtension(fileName);
                    if (!ArrayUtils.contains(extensionPermit, fileExtension)) {
                        result.setStatus(Contant.OPERATOR_FAILED);
                        result.setMsg("不支持该上传文件类型");
                        return result;
                    }
                    String[] a = fileName.split("\\.");
                    String saveDecompressPath = a[0];
                    String saveDecompressType = a[a.length - 1];
                    if (saveDecompressType.equals("zip")) {
                        saveZipDirectory = new File(saveZipPath);
                        if (!saveZipDirectory.exists()) {
                            saveZipDirectory.mkdirs();
                        }
                        System.out.println("saveZipDirectory*****Path:" + saveZipDirectory.getAbsolutePath());
                        // 将上传文件保存到目标文件中
                        File toFile = new File(saveZipDirectory.getAbsolutePath() + File.separator + fileName);
                        file.transferTo(toFile);
                        DecompressUtils.zipToFile(saveZipPath + fileName, saveProjectPath);

                        // 上传文件
                        uploadFile(fileName, saveZipPath, type);

                    } else if (saveDecompressType.equals("rar")) {
                        saveRarDirectory = new File(saveRarPath);
                        if (!saveRarDirectory.exists()) {
                            saveRarDirectory.mkdirs();
                        }
                        File toFile = new File(saveRarDirectory.getAbsolutePath() + File.separator + fileName);
                        file.transferTo(toFile);
                        DecompressUtils.rarToFile(saveRarPath + fileName, saveProjectPath);

                        // 上传文件
                        uploadFile(fileName, saveRarPath, type);

                    } else if (saveDecompressType.equals("json")) {
                        saveJsonDirectory = new File(saveJsonPath);
                        if (!saveJsonDirectory.exists()) {
                            saveJsonDirectory.mkdirs();
                        }
                        // 时间戳转换
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
                        String time = sdf.format(new Date(Long.valueOf(System.currentTimeMillis())));
                        File toFile = new File(saveJsonDirectory.getAbsolutePath() + File.separator + time + "_" + fileName);
                        file.transferTo(toFile);
                        // 上传文件
                        uploadFile(time + "_" + fileName, saveJsonPath, type);
                    }
                }
            }


        } catch (Exception e) {
            result.setStatus(Contant.OPERATOR_FAILED);
            result.setMsg("很抱歉，上传失败！");
            return result;
        }
        result.setStatus(Contant.OPERATOR_SUCCESS);
        result.setMsg("恭喜你，上传成功");
        return result;
    }

    /**
     * @Description
     * @Author 张逍
     * @Date 2019/7/26
     * @param fileName, path, type
     * @return com.acp.result.JsonData
     */
    public JsonData uploadFile(String fileName, String path, String type) {

        try {
            return uploadFileService.insert(UploadFile.builder().fileName(fileName).filePath(path).fileType(type).status("0").id(UUIDBuild.getUUID()).status("1").build());
        } catch (Exception e) {
            return JsonData.fail(911);
        }
    }


}
